package cn.tedu.csmall.commons.exception.handler;


import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.response.JsonResult;
import cn.tedu.csmall.commons.response.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ServiceExceptionHandler {

    ServiceExceptionHandler(){
        System.out.println("ServiceExceptionHandler.ServiceExceptionHandler");
    }

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handlerServiceException(ServiceException e){
        return JsonResult.fail(e);
    }

    @ExceptionHandler(Throwable.class)
    public JsonResult<Void> handlerThrowable(Throwable e){
        e.printStackTrace();
        return JsonResult.fail(ServiceCode.INTERNAL_SERVER_ERROR,"服务器忙,请稍后再试");
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handlerBindException(BindException e){
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.BAD_REQUEST,message);
    }
}
